#!/bin/bash

# 
# Edit 'srcd' or use argument 'libgdx.zip'
#
srcd=~/src/libgdx

function update_from_srcf {
 if [ -f "${srcf}" ]
 then
  if [ -d gdx ] 
  then
   rm -rf gdx
  fi
  mkdir gdx
  cd gdx
  #
  pwd
  #
  if unzip -qq ${srcf} '*.jar'
  then

   if [ ! -d ../lib ]
   then
    cd ..
    cat<<EOF>&2
Error, directory not found '$(pwd)/lib'
EOF
    exit 1
   fi
   cd ../lib
   #
   pwd
   #
   for natives in $(find ../gdx -type f -name '*-natives.jar')
   do
     mv ${natives} .

     rm -f ${natives}
   done
   cd ..
   if [ ! -d lib/src ]
   then
    mkdir -p lib/src
   fi
   cd lib/src
   #
   pwd
   #
   for sources in $(find ../../gdx -type f -name '*-sources.jar')
   do
     unzip -qqu ${sources} -x 'META-INF/*'

     rm -f ${sources}
   done
   cd ..
   #
   pwd
   #
   for jars in $(find ../gdx -type f -name '*.jar')
   do
     mv ${jars} .

     rm -f ${jars}
   done
   cd ..
   #
   pwd
   #
   rm -rf gdx

   cd lib
   #
   pwd
   #
   unzip -qqu ${srcf} '*LICENSE' 'README'
  else
   cat<<EOF>&2
Error, file unzip error, "${srcf}"
EOF
  fi
 else
  cat<<EOF>&2
Error, file not found, "${srcf}"
EOF
  exit 1
 fi
}

if [ "${1}" ]
then
 if [ -f "${1}" ]
 then
  if [ '.' = "$(dirname ${1})" ]
  then
   srcf="$(pwd)/${1}"
  else
   srcf="${1}"
  fi
  update_from_srcf
  exit 0
 else
  cat<<EOF
Usage: $0 [libgdx.zip]
EOF
  exit 1
 fi
else

 if [ -d ${srcd} ]
 then
  if srcf=$(ls ${srcd}/libgdx-*.zip ) && [ -f "${srcf}" ]
  then
   update_from_srcf
   exit 0
  else
   cat<<EOF>&2
Error, directory '${srcd}' requires 'ant' build.
EOF
   exit 1
  fi
 else
  cat<<EOF>&2
 Error, directory not found "${srcd}".  Edit script for location of libgdx.
EOF
  exit 1
 fi
fi
